package com.learn.problem;

import lombok.Data;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.concurrent.RecursiveTask;

/**
 * @author : Yu.Tan
 * @date : 2023/3/9 18:30
 * @desc : **
 * 斐波那契数列: 1、1、2、3、5、8、13、21、34、…… 公式 : F(1)=1，F(2)=1, F(n)=F(n-1)+F(n-2)(n>=3，n∈N*)
 */
public class Fibonacci {

    public static void main(String[] args) throws ExecutionException, InterruptedException {
        ForkJoinPool pool = new ForkJoinPool(10);
        long start = System.currentTimeMillis();
        for (int i = 0; i < 45; i++) {
            long fibonacciRecursion = fibonacciRecursion(i);
            System.out.println(fibonacciRecursion);
        }
        System.out.println("时间："+ (System.currentTimeMillis()-start));
        long start1 = System.currentTimeMillis();
        for (int i = 0; i < 45; i++) {
            FibonacciNum fibonacci = new FibonacciNum(i);
            ForkJoinTask<Integer> submit = pool.submit(fibonacci);
            System.out.println(submit.get());
        }
        System.out.println("时间："+ (System.currentTimeMillis()-start1));
    }

    @Data
    static class FibonacciNum extends RecursiveTask<Integer> {
        private int num;

        public FibonacciNum(int num){
            this.num=num;
        }

        @Override
        protected Integer compute() {
            if (num == 0 || num == 1) {
                return 1;
            }
            FibonacciNum fibonacciNum1 = new FibonacciNum(num - 1);
            FibonacciNum fibonacciNum2 = new FibonacciNum(num - 2);
            ForkJoinTask<Integer> fork1 = fibonacciNum1.fork();
            ForkJoinTask<Integer> fork2 = fibonacciNum2.fork();
            return fork1.join()+fork2.join();
        }
    }


    public static long fibonacciRecursion(long num) {
        if (num == 0 || num == 1) {
            return 1;
        }
        return fibonacciRecursion(num - 1) + fibonacciRecursion(num - 2);
    }


}
